class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {

        sort(nums.begin(), nums.end());

        int ans = nums[0] + nums[1] + nums[2];

        for(int i = 0; i < nums.size() - 2; i++)
        {
            int j = i + 1, k = nums.size() - 1;

            while(j < k)
            {
                int sum = nums[i] + nums[j] + nums[k];

                if(abs(ans - target) > abs(sum - target))
                {
                    ans = sum;
                }

                if(sum == target)
                {
                    ans = target;
                    break;
                }
                else if(ans < target)
                {
                    j++;
                }
                else k--;
            }
            
        }
        return ans;

    }
};

//the sum of the three numbers is the closest to the target value